package com.witmore.neutron.ai.web.wechat.ak;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AKSHARE 相关接口
 * Author: 豆子高
 * Date: 2025/7/21 13:41
 */
@Service
@Slf4j
public class AkShareHttpClient {


    /**
     * 执行GET请求并返回原始JSON字符串
     *
     * @param urlFormat URL格式
     * @param urlParams URL参数
     * @return 原始JSON响应字符串
     * @throws IOException 网络异常
     */
    public String executeGetRequestRaw(String urlFormat, Object... urlParams) throws IOException {
        String url = urlFormat;
        if (urlParams != null) {
            url = String.format(urlFormat, urlParams);
        }
        return this.executorGetHandlerRaw(url);
    }


    /**
     * GET请求执行处理器 - 返回原始JSON字符串
     *
     * @param url 完整请求URL
     * @return 原始JSON响应字符串
     * @throws IOException 网络异常
     */
    public String executorGetHandlerRaw(String url) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
            log.info("ak-tool executorGetHandlerRaw :{}", url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                log.info("executorGetHandlerRaw Response: {}", responseBody);
                return responseBody;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
